﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Xml.Linq;
using Shorten.Core.Data;
using Shorten.Core.Providers;
namespace Shorten.Core.Helpers
{
    public class ShortenHelper
    {
        public virtual XElement GetAllUrlsToXml()
        {
            var data = new ShortenDataContext();
            HttpContext.Current.Response.ContentType = "text/xml";
            XElement urls = new XElement("Shorten",
                
                    (from f in data.Urls
                     orderby f.Id
                     select
                     new XElement("Url",
                        new XAttribute("Id", f.Id),
                        new XElement("LongUrl", f.LongUrl),
                        new XElement("ShortUrl", Utility.GetSiteUrl() + f.ShortUrl))));
            return urls;
        }

        public static void GetShortenUrlXml()
        {
            ShortenHelper sh = new ShortenHelper();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "text/xml";
            HttpContext.Current.Response.Write(sh.GetAllUrlsToXml().ToString());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

        public virtual string GetAllUrlsToJson()
        {
            string json = string.Empty;

            json = "[{ \"Urls\": {";

            foreach (var f in ShortenManagement.GetAllUrls())
            {
                string format = String.Format("\"Id\":\"{0}\", \"LongUrl\":\"{1}\", \"ShortUrl\":\"{2}\"", f.Id, f.LongUrl, Utility.GetSiteUrl() + f.ShortUrl);
                json = json + "\"Url\": { " + format + "},";
               
            }

            return json = json.Trim(',') + " } }]";
        }

        public static void GetShortenUrlJson()
        {
            ShortenHelper sh = new ShortenHelper();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "text/x-json";
            HttpContext.Current.Response.Write(sh.GetAllUrlsToJson().ToString());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
    }
}
